// src/services/websocket.js - 简化版WebSocket服务
import { ElMessage } from 'element-plus'

class WebSocketService {
  constructor() {
    this.ws = null
    this.baseUrl = import.meta.env.DEV ? 'ws://localhost:8000/ws' : 'wss://your-domain.com/ws'
    this.conversationId = null
    this.messageHandlers = new Map()
    this.isConnected = false
  }

  // 连接WebSocket
  connect(conversationId) {
    if (!conversationId) {
      console.error('需要conversationId才能连接')
      return false
    }

    // 如果已连接同一会话，直接返回
    if (this.conversationId === conversationId && this.isConnected) {
      return true
    }

    // 断开现有连接
    this.disconnect()

    this.conversationId = conversationId
    const wsUrl = `${this.baseUrl}/${conversationId}`

    try {
      this.ws = new WebSocket(wsUrl)

      this.ws.onopen = () => {
        this.isConnected = true
        this.notifyHandlers('connection', { status: 'connected' })
      }

      this.ws.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data)
          this.handleMessage(data)
        } catch (error) {
          console.error('消息解析失败:', error)
        }
      }

      this.ws.onclose = () => {
        this.isConnected = false
        this.notifyHandlers('connection', { status: 'disconnected' })
      }

      this.ws.onerror = (error) => {
        console.error('WebSocket错误:', error)
        this.isConnected = false
      }

      return true
    } catch (error) {
      console.error('WebSocket连接失败:', error)
      return false
    }
  }

  // 处理消息
  handleMessage(data) {
    // 根据消息类型分发
    const { type } = data

    switch (type) {
      case 'history':
        this.notifyHandlers('history', data.messages)
        break

      case 'text_stream':
        this.notifyHandlers('text_stream', data.content)
        break

      case 'audio_stream':
        this.notifyHandlers('audio_stream', data.data)
        break

      case 'audio':
      case 'audio_complete':
        this.notifyHandlers('audio_complete', data.url)
        break

      case 'transcription':
        this.notifyHandlers('transcription', data.content)
        break

      default:
        this.notifyHandlers('message', data)
    }
  }

  // 发送文本消息
  sendTextMessage(content) {
    return this.send({
      type: 'text',
      content: content
    })
  }

  // 发送音频消息
  sendAudioMessage(audioData) {
    // 转换为Base64
    const base64Audio = this.arrayBufferToBase64(audioData)

    return this.send({
      type: 'audio',
      data: base64Audio
    })
  }

  // 基础发送方法
  send(data) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(JSON.stringify(data))
      return true
    }
    return false
  }

  // ArrayBuffer转Base64
  arrayBufferToBase64(buffer) {
    const bytes = new Uint8Array(buffer)
    let binary = ''
    for (let i = 0; i < bytes.length; i += 8192) {
      const chunk = bytes.subarray(i, i + 8192)
      binary += String.fromCharCode.apply(null, chunk)
    }
    return btoa(binary)
  }

  // 注册消息处理器
  onMessage(type, handler) {
    if (!this.messageHandlers.has(type)) {
      this.messageHandlers.set(type, [])
    }
    this.messageHandlers.get(type).push(handler)
  }

  // 移除消息处理器
  offMessage(type, handler) {
    if (handler) {
      const handlers = this.messageHandlers.get(type)
      if (handlers) {
        const index = handlers.indexOf(handler)
        if (index > -1) handlers.splice(index, 1)
      }
    } else {
      this.messageHandlers.delete(type)
    }
  }

  // 通知处理器
  notifyHandlers(type, data) {
    const handlers = this.messageHandlers.get(type) || []
    handlers.forEach(handler => handler(data))
  }

  // 断开连接
  disconnect() {
    if (this.ws) {
      this.ws.close()
      this.ws = null
    }
    this.isConnected = false
  }

  // 获取连接状态
  getConnectionStatus() {
    return {
      connected: this.isConnected,
      conversationId: this.conversationId
    }
  }
}

// 创建单例
export const websocketService = new WebSocketService()
export default websocketService